import sys
sys.path.append("../")

from model.CommonDb import *
from controller.BaseController import *
import time

class ProjectQueueController(BaseController):
    def __init__(self,args):
        super(ProjectQueueController,self).__init__(args)
        self.table = "deploy_queue"

    def run(self):
        if self.args["func"] == "getColumns":
            return self.getAllColumns(self.args["fields"])
        elif self.args["func"] == "getMap":
            return self.getMap(self.args["fields"])
        elif self.args["func"] == "getAllData":
            return self.getAllData()
        elif self.args["func"] == "getAllMapData":
            return self.getAllMapData()
        elif self.args["func"] == "getData":
            return self.getData(self.args["fields"],self.args["page"],self.args["num"],self.args["orderfield"],self.args["asc"])
        elif self.args["func"] == "getRowData":
            return self.getRowData(self.args["fields"], self.args["id"])
        elif self.args["func"] == "update":
            return self.update(self.args["data"])
        elif self.args["func"] == "add":
            return self.add(self.args["data"])
        elif self.args["func"] == "delete":
            return self.delete(self.args["data"])
        elif self.args["func"] == "addDeployQueue":
            return self.addDeployQueue(self.args["data"])

    def getAllColumns(self,fields):
        db = CommonDb(self.table)
        rs = db.getAllColumns(fields)
        columns = []
        for row in rs:
            option = {'field': row["field"], 'title': row["comment"], 'sort': 'true', 'fixed': 'left'}
            columns.append(option)
        columns.append({'fixed': 'right', 'title':'操作', 'width':'200', 'align':'center', 'toolbar': '#barDemo'})
        return columns

    def update(self,data):
        db = CommonDb(self.table)
        return db.update(data," id="+str(data["id"]))

    def add(self,data):
        db = CommonDb(self.table)
        return db.add(data,True)

    def addDeployQueue(self,data):
        db = CommonDb("projects_map")
        git_repos_id,git_uri = data["git_data"].split("|")
        server_id,server_ip = data["host_data"].split("|")
        version_no = data["version_no"]
        newdata = {
            "project_id" : data["id"],
            "git_repos_id" : git_repos_id,
            "server_id" : server_id,
            "version_no" : version_no
        }
        self.executeCmd(newdata, version_no, git_uri, data["project_name"])
        return db.add(newdata)

    def executeCmd(self,config,version_no,git_uri,project_name):
        con = BaseController({"a": "a"})
        print("=====================生成镜像配置文件=====================================")
        con.sendCmd("sudo rm -rf /home/rancher/playhook/deploy.yml")
        con.sendCmd("cp /home/rancher/playhook/install.yml /home/rancher/playhook/deploy.yml")
        con.sendCmd("echo '  vars:' >> /home/rancher/playhook/deploy.yml")
        con.sendCmd("echo '    host: \"localhost\"' >> /home/rancher/playhook/deploy.yml")
        con.sendCmd(
            "echo '    git_repo_url: \"" + git_uri + "\"' >> /home/rancher/playhook/deploy.yml")
        con.sendCmd("echo '    clone_dest_path: \"/tmp/repo\"' >> /home/rancher/playhook/deploy.yml")
        con.sendCmd("echo '    git_branch: \"master\"' >> /home/rancher/playhook/deploy.yml")
        con.sendCmd("echo '    docker_image_name: \"" + project_name + "\"' >> /home/rancher/playhook/deploy.yml")
        con.sendCmd("echo '    docker_image_tag: \"" + version_no + "\"' >> /home/rancher/playhook/deploy.yml")
        con.sendCmd("echo '    out_port: \"9910\"' >> /home/rancher/playhook/deploy.yml")
        con.sendCmd("echo '    in_port: \"9910\"' >> /home/rancher/playhook/deploy.yml")
        time.sleep(20)
        try:
            print("=====================生成镜像文件=====================================")
            con.sendCmd("ansible-playbook /home/rancher/playhook/deploy.yml > /home/rancher/playhook/log.out")
        except:
            pass
        time.sleep(20)
        print("=====================生成容器配置文件=====================================")
        con.sendCmd("sudo rm -rf /home/rancher/playhook/deploy1.yml")
        con.sendCmd("cp /home/rancher/playhook/install1.yml /home/rancher/playhook/deploy1.yml")
        con.sendCmd("echo '  vars:' >> /home/rancher/playhook/deploy1.yml")
        con.sendCmd("echo '    host: \"localhost\"' >> /home/rancher/playhook/deploy1.yml")
        con.sendCmd(
            "echo '    git_repo_url: \"" + git_uri + "\"' >> /home/rancher/playhook/deploy1.yml")
        con.sendCmd("echo '    clone_dest_path: \"/tmp/repo\"' >> /home/rancher/playhook/deploy1.yml")
        con.sendCmd("echo '    git_branch: \"master\"' >> /home/rancher/playhook/deploy1.yml")
        con.sendCmd("echo '    docker_image_name: \"" + project_name + "\"' >> /home/rancher/playhook/deploy1.yml")
        con.sendCmd("echo '    docker_image_tag: \"" + version_no + "\"' >> /home/rancher/playhook/deploy1.yml")
        con.sendCmd("echo '    out_port: \"9910\"' >> /home/rancher/playhook/deploy1.yml")
        con.sendCmd("echo '    in_port: \"9910\"' >> /home/rancher/playhook/deploy1.yml")
        time.sleep(20)
        print("=====================安装容器=====================================")
        con.sendCmd("ansible-playbook /home/rancher/playhook/deploy1.yml > /home/rancher/playhook/log1.out")


    def delete(self,data):
        db = CommonDb(self.table)
        print(data)
        return db.delete_where(" id="+str(data["id"]))

    def getMap(self,fields):
        db = CommonDb(self.table)
        rs = db.getAllColumns(fields)
        map = {}
        for row in rs:
            map[row["field"]] = {"title":row["comment"],"type":row["type"]}
        return map


    def getData(self,fields,page,num,orderfield,asc):
        db = CommonDb(self.table)
        fieldstr = ""
        for option in fields:
            fieldstr += option + ","
        rs = db.getPageData(fieldstr[0:-1],"1",page,num,orderfield,asc)
        return rs

    def getAllData(self):
        db = CommonDb(self.table)
        return db.selectAll("1","*",True)

    def getAllMapData(self):
        db = CommonDb(self.table)
        sql = ("select gr.ip,gr.username,gr.password,gr.uri,"
               " s.uri as s_uri,"
               " sr.ip,sr.username,sr.password,sr.uri"
               "from deploy_queue dq,git_repos gr,softs s,source_repos sr"
               "where dq.git_data=gr.id "
               " and dq.package_type=s.id "
               " and dq.repos_data=sr.id ")
        return db.executeByMap(sql,["gr_ip",""])

    def getRowData(self,fields,id):
        columns = self.getMap(fields)
        print(columns)
        db = CommonDb(self.table)
        fieldstr = ""
        for option in fields:
            fieldstr += option + ","
        rs = db.getRowData(fieldstr[0:-1]," id="+id)

        return rs